package web.ling.por

import grails.converters.JSON

import java.text.SimpleDateFormat

class ProviderController {

    def providerService
    def grailsApplication

    def listOpenOrders() {

        OrderStatus orderStatus = OrderStatus.findByDescription('open')
        Provider tempProvider = Provider.getAll().first()   //TODO should get current user (from session?)
        ArrayList <FieldOfExpertise> fieldsOfExpertise = tempProvider.fieldsOfExpertise
        ArrayList <Language> languages = tempProvider.languages
        ArrayList<ProofreadingOrder> allOpenOrders = ProofreadingOrder.findAllByOrderStatusAndFieldOfExpertiseInListAndLanguageInList(
                orderStatus,
                fieldsOfExpertise,
                languages,
                [sort: "submissionDate"])

        def bankfee = grailsApplication.config.ling.por.prices.paypal.percent
        def usfee = grailsApplication.config.ling.por.prices.us.percent

        def appliedTo = Application.findAllByProvider(tempProvider)
        def openOrders = allOpenOrders.minus(appliedTo.collect {it.order})
        return [bankfee: bankfee, usfee: usfee, catname: g.message(code: 'navigation.orders'), openOrders: openOrders, appliedTo: appliedTo]
    }

    def apply() {

        def bankfee = grailsApplication.config.ling.por.prices.paypal.percent
        def usfee = grailsApplication.config.ling.por.prices.us.percent

        Provider tempProvider = Provider.getAll().first()   //TODO should get current user (from session?)
        ProofreadingOrder order = ProofreadingOrder.findById(params.id)
        if(providerService.checkIfCanApply(tempProvider, order)) {
            Application app = new Application(order: order)
            if(params.price?.isBigDecimal()) {
                app.price = params.price.toBigDecimal()
            }
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd")
                Date canStart = dateFormat.parse(params.canStart)
                Date canFinish = dateFormat.parse(params.canFinish)
                app.canStart = canStart
                app.canFinish = canFinish
                app.provider = tempProvider
                order.applyingProviders.add(app)
            } catch (Exception e) {
                render "error"
                return
            }
            if(app.save()) {

            } else {
                render "error"
                return
            }

            order = order.merge()
            def renderedOrder = g.render(template: "templates/application", model: [app: app, usfee: usfee, bankfee: bankfee])
            render ([source: renderedOrder, id: order.id] as JSON)
            return
        } else {
            render "error"
            return
        }

    }

    def remove() {
        Provider tempProvider = Provider.getAll().first()   //TODO should get current user (from session?)
        ProofreadingOrder order = ProofreadingOrder.findById(params.id)
        if(providerService.checkIfCanRemove(tempProvider, order)) {
            Application.findByOrderAndProvider(order, tempProvider).delete()
            order.applyingProviders.remove(Application.findByOrderAndProvider(order, tempProvider))
            order = order.merge()
            def renderedOrder = g.render(template: "templates/order", model: [order: order, open: true])
            render ([source: renderedOrder, id: order.id] as JSON)
            return
        } else {
            render "error"
            return
        }
    }

}
